package cn.itcast;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.core5.http.io.entity.EntityUtils;

import javax.swing.text.html.parser.Entity;

public class HttpClientPoolTestDemo {

    public static void main(String[] args) {
        PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
        //设置连接数---httpclient对象
        poolingHttpClientConnectionManager.setMaxTotal(100);
        //设置每台主机的对象数
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(10);//避免主机分配的client对象不均匀 导致极端情况出现
        //一些网址爬的特别快 而一些网址分配不到client对象无法发送请求而导致爬取缓慢

        doGet(poolingHttpClientConnectionManager);
    }

    public static void doGet(PoolingHttpClientConnectionManager poolingHttpClientConnectionManager) {
        //就相当于创建httpClient对象 这里只不过是从池子里面直接取
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager).build();
        //后续发送get请求就是一样的
        HttpGet httpGet = new HttpGet("http://yun.itheima.com/search");
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            if (response.getCode() == 200) {
                String entity = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //客户端不用去关闭 但是响应需要关闭
                if (response != null) {
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }


}
